package NG::Sys::Cached::DBRow;
use strict;
use warnings;
use utf8;

use base 'NG::Sys::Cached::Base';

sub init {
	my ($self) = @_;
	$self->SUPER::init;
	unless($self->{table}){
		die "need table\n";
	}
	unless($self->{pkey}){
		die "need pkey\n";
	}
	if(grep {$self->{pkey} eq $_} @{$self->{fields}}){
		die $self->{pkey}." present in fields\n";
	}
	unless($self->{dbh}){
		die "need dbh";
	}
	$self->{sth}{read} = $self->{dbh}->prepare("select * from `".$self->{table}."` where `".$self->{pkey}."`=?");
	$self->{sth}{remove} = $self->{dbh}->prepare("delete from `".$self->{table}."` where `".$self->{pkey}."`=?");
}
sub need_create {
	return 1;
}
sub _read_source {
	my ($self,$id) = @_;
	my $sth = $self->{sth}{read};
	$sth->execute($id);
	return $sth->fetchrow_hashref;
}
sub _remove_source {
	my ($self,$id) = @_;
	my $sth = $self->{sth}{remove};
	$sth->execute($id);
}
sub _update_source {
	unshift @_,"update";
	goto &__store_source;
}
sub _replace_source {
	unshift @_,"replace";
	goto &__store_source;
}
sub __store_source {
	my ($type,$self,$id,$data,$keys) = @_;
	unless($keys and @$keys){
		return 0;
	}
	my @skeys = sort @$keys;
	my $key = ":".$type.":".join(":",@skeys);
	my $sth;
	unless($sth = $self->{sth}{$key}){
		my $sql = $type." `$self->{table}` set ".join(", ", map {'`'.$_.'`=?'} @skeys);
		if($type eq "replace"){
			$sql .= ", `$self->{pkey}`=?";
		}else{
			$sql .= " where `$self->{pkey}`=?";
		}
		$sth = $self->{sth}{$key} = $self->{dbh}->prepare($sql);
	}
	$sth->execute(@{$data}{@skeys},$id);
	return $keys;
}
sub create {
	my $self = shift;
	my $data;
	unless(@_){
		$data = {};
	}elsif(ref $_[0]){
		$data = shift;
	}else{
		if(@_ % 2){
			die "odd number params\n";
		}
		$data = {@_};
	}
	my $new_id = $self->{dbh}->Insert($self->{table},$data);
	if(my $id = $data->{$self->{pkey}}){
		$new_id = $id;
	}
	return $self->get_obj($new_id);
}


1;
